//
//  SettingViewController.m
//  WDFans
//
//  Created by Zhihong Yuan on 1/31/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SettingViewController.h"
#import "AboutUsViewController.h"
#import "UIFont+Utilities.h"
#import "ChangeInfoViewController.h"
#import "ZHDataService.h"
#import "ActivityViewManager.h"
#import "LoginViewController.h"
#import "NSString+Utilities.h"
#import "FontViewController.h"
#import "MoreNewsViewController.h"
#import "AccountViewController.h"



@implementation SettingViewController

@synthesize myTableView;
@synthesize  keyDict;

#pragma mark - View lifecycle
- (void)dealloc
{
    [keyDict release];
    [myTableView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)initTableKeys
{
    NSArray *array1 = [NSArray arrayWithObjects:@"账号管理", nil];
    NSArray *array2 = [NSArray arrayWithObject:@"正文字体"];
    NSArray *array3 = [NSArray arrayWithObjects:@"个人收藏",@"服务条款",@"免责声明", nil];
    NSArray *array4 = [NSArray arrayWithObject:@"手动清除缓存"];
    self.keyDict = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:array1,array2,array3,array4, nil] forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3", nil]];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [myTableView reloadData];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"设置";
    myTableView.backgroundColor = [UIColor clearColor];
    [self setBackgroundImageViewForTabView];
    
    [self addNaviBarRightItemWithTitle:@"关于"];
    [self initTableKeys];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.myTableView = nil;
    self.keyDict = nil;
}


#pragma mark - implemeted absract methods in abstract class
- (void)rightItemClicked
{
    AboutUsViewController *aboutController = [[AboutUsViewController alloc] init];
    [self.navigationController pushViewController:aboutController animated:YES];
    [aboutController release];
}


#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key = [NSString stringWithFormat:@"%d",section];
    return [[self.keyDict objectForKey:key] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    NSInteger section = [indexPath section];
    NSString *key = [NSString stringWithFormat:@"%d",section];
    
    if(section == 0)
    {
        static NSString *cellIdentify2 = @"cellIdentify2";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify2];
        if(cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentify2] autorelease];
            cell.textLabel.textColor = [UIColor cellLeftKeyTextColor];
            cell.textLabel.font = [UIFont getSettingViewTableCellLabelFont];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = @"账户设置";
        return cell;
    }
    else
    {
        static NSString *cellIdentify = @"cellIdentify";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
        if(cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentify] autorelease];
            cell.textLabel.textColor = [UIColor cellLeftKeyTextColor];
            cell.textLabel.font = [UIFont getSettingViewTableCellLabelFont];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        
        // 字体
        if(section == 1)
        {
            UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(260, 12, 20, 20)];
            label.backgroundColor = [UIColor clearColor];
            label.highlightedTextColor = [UIColor whiteColor];
            label.font = cell.textLabel.font;
            NSString *font = (NSString *)[[NSUserDefaults standardUserDefaults] objectForKey:kFontKey];
            if(font == nil)
            {
                label.text = @"中";
            }
            else 
            {
                label.text = font;
            }
            
            [cell addSubview:label];
            [label release];
            
        }
        else if(section == 3)
            cell.accessoryType = UITableViewCellAccessoryNone;
        cell.textLabel.text = [[self.keyDict objectForKey:key] objectAtIndex:row];
        return cell;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[self.keyDict allKeys] count];
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    if(section == 0)
//        return @"绑定账户";
//    else
//        return @"综合信息";
//}

#pragma mark - UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        AccountViewController *accountViewController = [[AccountViewController alloc] initWithNibName:@"AccountViewController" bundle:nil];
        [self.navigationController pushViewController:accountViewController animated:YES];
        [accountViewController release];
        
    }
    else
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        if(indexPath.section == 2)
        {
            if(indexPath.row == 0)
            {
                
                NSString *path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
                
                NSString *filename=[path stringByAppendingPathComponent:@"WDNews"]; 
                NSData *fileData=[NSData dataWithContentsOfFile:filename];
                NSMutableArray* array = [NSKeyedUnarchiver unarchiveObjectWithData:fileData];
                
                if (array == nil|| [array count]==0) {
                    [ActivityViewManager showErrorViewWithMessage:@"无收藏内容"];
                    return;
                }
                
                self.navigationController.navigationBar.hidden = YES;
                
                MoreNewsViewController *moreNewsController = [[MoreNewsViewController alloc] initWithFirstPageNews:array andNextPage:NO];
                moreNewsController.isEditMode = YES;
                
                [self.navigationController pushViewController:moreNewsController animated:YES];
                [moreNewsController release];
                
            }
            else if(indexPath.row == 1)
            {

            }
            else
            {
                
            }
        }
        else if(indexPath.section == 1)
        {
            FontViewController *fontController = [[FontViewController alloc] init];
            [self.navigationController pushViewController:fontController animated:YES];
            [fontController release];
        }
        else
        {
            NSFileManager *manager = [NSFileManager defaultManager];
            NSError *error = nil;
            if([manager fileExistsAtPath:[NSString getImagesDirectory]])
            {
                [manager removeItemAtPath:[NSString getImagesDirectory] error:&error];
            }
            if(nil == error)
            {
                [ActivityViewManager showErrorViewWithMessage:@"缓存清理完毕"];
            }
            else
                [ActivityViewManager showErrorViewWithMessage:error.description];
        }
    }
}

#pragma mark - AccountLinkCellDelegate methods
- (void)didLinkOrUnlinkAccount:(AccountLinkCell *)accountCell
{
    if([accountCell.accountName.text isEqualToString:@"新浪微博"])
    {
        if(accountCell.linkSwitch.on)
        {
//            [ZHDataService sharedService].weibo.delegate = self;
//            [[ZHDataService sharedService].weibo startAuthorize];
        }
        else
        {
//            [ZHDataService sharedService].weibo.delegate = self;
//            [[ZHDataService sharedService].weibo LogOut];
        }
    }
    else
    {
        if(accountCell.linkSwitch.on)
            [self.tabBarController setSelectedIndex:1];
        else
            [ZHDataService logout];
    }
}

#pragma mark - WBSessionDelegate methods
- (void)weiboDidLogin
{
    [myTableView reloadData];
    [ActivityViewManager showErrorViewWithMessage:@"新浪微博绑定成功！"];
}
- (void)weiboLoginFailed:(BOOL)userCancelled withError:(NSError*)error
{
    [myTableView reloadData];
    [ActivityViewManager showErrorViewWithMessage:@"新浪微博绑定失败！"];
}

- (void)weiboDidLogout
{
    [myTableView reloadData];
    [ActivityViewManager showErrorViewWithMessage:@"新浪微博取消绑定！"];
    
}
@end
